import React, { Component } from 'react';
import { Card, Descriptions, Button } from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import { routerRedux } from 'react-router-dom';
import moment from 'moment';

const logTypeHash = {
  1: 'OMS提醒',
  2: '告警提醒',
  3: 'vin码冲突',
  4: '诊断上报',
  5: 'can网络异常',
  6: 'E-CALL',
  7: '三级告警',
};
const tempHash = {
  1: {
    protocolVersion: '协议版本号',
    vin: '设备vin码',
    vinTag: '设备vin标识',
    messageId: '消息ID',
    serviceType: '服务类型',
    messageType: '消息类型',
    timeStamp: '消息发送时间',
    messageProtocolVersion: '消息版本号',
    contentSize: '数据长度',
    collectTime: '数据收集时间',
    lon: '经度',
    lat: '纬度',
    omsType: {
      label: 'OMS提醒',
      0: '无报警',
      1: '儿童遗留报警',
      2: '宠物遗留报警',
      3: '特殊物品遗留监控',
    },
    bodyHexStr: '原始报文',
  },
  2: {
    protocolVersion: '协议版本号',
    vin: '设备vin码',
    vinTag: '设备vin标识',
    messageId: '消息ID',
    serviceType: '服务类型',
    messageType: '消息类型',
    timeStamp: '消息发送时间',
    messageProtocolVersion: '消息版本号',
    contentSize: '数据长度',
    instrusionAlert: '防盗提醒',
    collideAlert: '车辆碰撞报警',
    breakSentryAlert: '哨兵模式退出提醒',
    coAlert: '一氧化碳告警',
    co2Alert: '二氧化碳告警',
    insulationAlert: {
      label: '插枪保温提醒',
      1: '到预计时间提醒',
      2: '故障提醒',
    },
    doorUnLockAlert: '车门未锁提醒',
    keyLostAlert: '钥匙遗忘提醒',
    batteryFeedAlert: '蓄电池馈电提醒',
    bodyHexStr: '原始报文',
  },
  3: {
    protocolVersion: '协议版本号',
    vin: '设备vin码',
    vinTag: '设备vin标识',
    messageId: '消息ID',
    serviceType: '服务类型',
    messageType: '消息类型',
    timeStamp: '消息发送时间',
    messageProtocolVersion: '消息版本号',
    contentSize: '数据长度',
    vinVehicle: 'tbox上报的VIN',
    imei: 'IMEI',
    imsi: 'IMSI',
    langage: {
      label: '插枪保温提醒',
      0: '法语',
      1: '英语',
      2: '德语',
      3: '西班牙语',
      4: '意大利语',
      5: '葡萄牙语',
      6: '荷兰语',
      7: '希腊语',
      8: '巴西葡萄牙语',
      9: '繁体中文',
      10: '简体中文',
      11: '土耳其语',
      12: '日语',
      13: '俄语',
    },
    detailedVersions: '版本信息',
    software: 'MCU软件版本',
    hardware: 'Modem版本',
    cpu: '软件版本',
    firmware: '硬件版本',
    bodyHexStr: '原始报文',
  },
  4: {
    protocolVersion: '协议版本号',
    vin: '设备vin码',
    vinTag: '设备vin标识',
    messageId: '消息ID',
    serviceType: '服务类型',
    messageType: '消息类型',
    timeStamp: '消息发送时间',
    messageProtocolVersion: '消息版本号',
    contentSize: '数据长度',
    dtcsList: 'DTC 错误码信息',
    bodyHexStr: '原始报文',
  },
  5: {
    protocolVersion: '协议版本号',
    vin: '设备vin码',
    vinTag: '设备vin标识',
    messageId: '消息ID',
    serviceType: '服务类型',
    messageType: '消息类型',
    timeStamp: '消息发送时间',
    messageProtocolVersion: '消息版本号',
    contentSize: '数据长度',
    collectTime: '数据采集时间',
    longitude: '经度',
    latitude: '纬度',
    monitoringTimer: '网络监控计时器的值',
    abnormalMonitoringCounter: '整车网络异常计数器的值',
    wakeupCounter: '唤醒计数器的值',
    batteryStatus: {
      label: '整车电源状态',
      0: 'OFF档',
      1: '非OFF档',
    },
    // otherStatus: '0-未休眠(频繁唤醒+无法进入休眠) 1-休眠 2-未休眠(无法进入休眠) 3-未休眠(频繁唤醒)',
    bodyHexStr: '原始报文',
  },
  6: {
    protocolVersion: '协议版本号',
    vin: '设备vin码',
    vinTag: '设备vin标识',
    messageId: '消息ID',
    serviceType: '服务类型',
    messageType: '消息类型',
    timeStamp: '消息发送时间',
    messageProtocolVersion: '消息版本号',
    contentSize: '数据长度',
    lonlat: '位置信息',
    direction: '车头朝向',
    faultType: {
      label: '故障类型',
      0: '主动',
      1: '碰撞',
    },
    bodyHexStr: '原始报文',
  },
  7: {}
};
const ecuHash = {
  cgwPCANSleepState: '动力网段休眠状态',
  cgwCCANSleepState: '底盘网段休眠状态',
  cgwICANSleepState: '影音网段休眠状态',
  cgwBCANSleepState: '车身网段休眠状态',
  gwEMSSleepError: 'EMS休眠异常',
  gwESCSleepError: 'ESC休眠异常',
  gwTCUSleepError: 'TCU休眠异常',
  gwSASSleepError: 'SAS休眠异常',
  gwBCMSleepError: 'BCM休眠异常',
  gwACSleepError: 'AC休眠异常',
  gwADPSleepError: 'ADP休眠异常',
  gwEPSSleepError: 'EPS休眠异常',
  gwFAPASleepError: 'FAPA休眠异常',
  gwMP5SleepError: 'MP5休眠异常',
  gwAVMSleepError: 'AVM休眠异常',
  gwTBOXSleepError: 'TBOX休眠异常',
  gwMFTSSleepError: 'MFTS休眠异常',
  gwICSleepError: 'IC休眠异常',
  gwSCCSleepError: 'SCC休眠异常',
  gwCAMERASleepError: 'CAMERA休眠异常',
  gwRADARSleepError: 'RADAR休眠异常',
  gwESMSleepError: 'ESM休眠异常',
  gwACUSleepError: 'ACU休眠异常',
  gwADASCSleepError: 'ADASC休眠异常',
  gwBSDSleepError: 'BSD休眠异常',
  gwBSDSSleepError: 'BSD_S休眠异常',
  gwAMPSleepError: 'AMP休眠异常',
  gwHCMLSleepError: 'HCML休眠异常',
  gwHCMRSleepError: 'HCMR休眠异常',
  gwPDCSleepError: 'PDC休眠异常',
  cgwHcanSleepState: '新能源网段休眠状态',
  gwVECUSleepError: 'VECU休眠异常',
  gwHTCUSleepError: 'HTCU休眠异常',
  gwMCUSleepError: 'MCU休眠异常',
  gwGCUSleepError: 'GCU休眠异常',
  gwBMSSleepError: 'BMS休眠异常',
  gwDCDCSleepError: 'DCDC休眠异常',
  gwAVASSleepError: 'AVAS休眠异常',
  gwCCMSleepError: 'CCM休眠异常',
  gwAPMSleepError: 'APM休眠异常',
  gwADASSleepError: 'ADAS休眠异常',
  gwPOTSleepError: 'POT休眠异常',
  gwCWPSleepError: 'CWP休眠异常',
  gwARTOCSleepError: 'ARTOC休眠异常',
  gwOMSSleepError: 'OMS休眠异常',
  gwDMSCSleepError: 'DMSC休眠异常',
  reservedSignal17: '预留字段17',
  reservedSignal18: '预留字段18',
  reservedSignal19: '预留字段19',
  reservedSignal20: '预留字段20',
};
const mapStateToProps = (state: any) => ({
  connectPlat: state.connectPlat,
  menu: state.menu,
  loading: state.loading.models['connectPlatLog'],
});
class VehicleReportLogDetail extends Component<any, any> {
  state = {
    reportType: JSON.parse(sessionStorage.getItem('vehicleReportLogData') || '')?.reportType,
    logId: JSON.parse(sessionStorage.getItem('vehicleReportLogData') || '')?.id,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { logId } = this.state;

    dispatch({
      type: 'connectPlat/queryDetail',
      payload: { id: logId },
    });
  }

  handleFreshPage = () => {
    const {
      connectPlat: {
        connectReportLog: { pagination },
      },
      dispatch,
    } = this.props;
    const { current, pageSize } = pagination;
    let params = { pageNo: current, pageSize: pageSize };
    dispatch({
      type: 'connectPlat/queryList',
      payload: { ...params },
    });
  };
  goBack = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/connectPlat/vehicleReportLogQuery', sourcePage: 'vehicleReportLogDetail' }));
  };
  /**
   * 是否json字符串类型
   * @param str
   */
  isJsonString = (str: string) => {
    try {
      if (JSON.parse(str) && typeof JSON.parse(str) === 'object') {
        return true;
      }
    } catch (e) {}
    return false;
  };
  render() {
    const {
      connectPlat: { connectReportLogDetail },
    } = this.props;
    const { reportType } = this.state;
    const detail = connectReportLogDetail?.reportDetail;
    const json = this.isJsonString(detail) ? JSON.parse(detail) : {};
    const data = {
      bodyHexStr: json?.bodyHexStr,
      ...json?.data?.header,
      ...json?.data?.body,
      ...json?.data?.body?.coordinates,
      ...json?.data?.body?.vehicleBatteryStatus,
    };
    const ecuData = json?.data?.body?.ecuSignal || {};
    const jsonTempHash = tempHash[reportType];
    const itemList = Object.keys(jsonTempHash).map(key => {
      if (reportType == 1) {
        // osm
        return {
          label: key !== 'omsType' ? jsonTempHash[key] : jsonTempHash[key].label,
          value:
            key !== 'omsType'
              ? ['timeStamp'].includes(key)
                ? data[key] && moment(data[key] * 1000).format('YYYY-MM-DD HH:mm:ss')
                : data[key] || '-'
              : jsonTempHash['omsType'][data['omsType']],
        };
      } else if (reportType == 2) {
        // 告警
        return {
          label: key !== 'insulationAlert' ? jsonTempHash[key] : jsonTempHash[key].label,
          value:
            key !== 'insulationAlert'
              ? ['timeStamp'].includes(key)
                ? data[key] && moment(data[key] * 1000).format('YYYY-MM-DD HH:mm:ss')
                : data[key] || '-'
              : jsonTempHash['insulationAlert'][data['insulationAlert']],
        };
      } else if (reportType == 3) {
        // vin
        return {
          label: key !== 'langage' ? jsonTempHash[key] : jsonTempHash[key].label,
          value:
            key !== 'langage'
              ? ['timeStamp'].includes(key)
                ? data[key] && moment(data[key] * 1000).format('YYYY-MM-DD HH:mm:ss')
                : data[key] || '-'
              : jsonTempHash['langage'][data['langage']],
        };
      } else if (reportType == 4) {
        // 诊断异常
        return {
          label: jsonTempHash[key],
          value: ['timeStamp'].includes(key)
            ? data[key] && moment(data[key] * 1000).format('YYYY-MM-DD HH:mm:ss')
            : data[key] || '-',
        };
      } else if (reportType == 5) {
        // can网络异常
        return {
          label: key !== 'batteryStatus' ? jsonTempHash[key] : jsonTempHash[key].label,
          value:
            key !== 'batteryStatus'
              ? ['timeStamp'].includes(key)
                ? data[key] &&
                  !isNaN(parseFloat(data[key])) &&
                  moment(data[key] * 1000)
                    // .utc()
                    .format('YYYY-MM-DD HH:mm:ss')
                : data[key] || '-'
              : jsonTempHash['batteryStatus'][data['batteryStatus']],
        };
      } else if (reportType == 6) {
        // const lonlat = parseFloat(data['longitude'] || '0').toFixed(6) + ',' + parseFloat(data['latitude'] || '0').toFixed(6)
        // const direction = data['direction'] == 0 ? '正北' : `正北偏${data['direction']}度`;
        return {
          label: key !== 'faultType' ? jsonTempHash[key] : jsonTempHash[key].label,
          value: key === 'lonlat' 
                  ? parseFloat(data['longitude'] || '0').toFixed(6) + ',' + parseFloat(data['latitude'] || '0').toFixed(6) 
                  : key === 'direction'
                  ? (data['direction'] == 0 ? '正北' : `正北偏${data['direction']}度`)
                  : ['timeStamp'].includes(key)
                  ? data[key] &&
                      !isNaN(parseFloat(data[key])) &&
                      moment(data[key] * 1000)
                        // .utc()
                        .format('YYYY-MM-DD HH:mm:ss')
                  : key === 'faultType' 
                  ? jsonTempHash['faultType'][data['faultType']]
                  : data[key] || '-'
        }
      } else {
        return false;
      }
    });
    const ecuList =
      reportType == 5
        ? Object.keys(ecuHash).map(key => {
            return {
              label: ecuHash[key],
              value: ecuData[key] || '-',
            };
          })
        : [];
    return (
      <div className={styles.container}>
        <Card bordered={false}>
          <Descriptions
            title={logTypeHash[reportType]}
            bordered
            column={{ lg: 3, md: 3, sm: 2, xs: 1 }}
          >
            {itemList.map(item => {
              return <Descriptions.Item label={item['label']}>{item['value']}</Descriptions.Item>;
            })}
          </Descriptions>
          {reportType == 5 && (
            <>
              <p style={{ margin: '10px 0' }}>ECU状态</p>
              <Descriptions bordered column={{ lg: 3, md: 3, sm: 2, xs: 1 }}>
                {ecuList.map(item => {
                  return (
                    <Descriptions.Item label={item['label']}>{item['value']}</Descriptions.Item>
                  );
                })}
              </Descriptions>
            </>
          )}
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <Button type="primary" key="back" onClick={this.goBack}>
              关闭
            </Button>
          </div>
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(VehicleReportLogDetail);
